package com.kkb.shopcenter.controller;

import com.github.pagehelper.PageInfo;
import com.kkb.shopcenter.api.GoodInfoService;
import com.kkb.shopcenter.common.common.HttpResult;
import com.kkb.shopcenter.common.pojo.GoodsAttach;
import com.kkb.shopcenter.common.pojo.GoodsInfo;
import com.kkb.shopcenter.common.pojo.GoodsQueryCondition;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("api")
public class GoodsInfoController {

    @Reference
    private GoodInfoService goodInfoService;

    /**
     * 获取商品列表
     * @param condition 查询条件
     * @return
     */
    @PostMapping(value = "/queryGoodsList")
    public HttpResult queryGoodsList(@RequestBody GoodsQueryCondition condition){
        PageInfo<GoodsInfo> goods =goodInfoService.queryAllByCondition(condition);
        return HttpResult.success(goods);
    }

    /**
     * 关联图片与商品的映射关系
     * @param map
     * @return
     */
    @ResponseBody
    @PostMapping("/relatedImg")
    public HttpResult reletedImg(@RequestBody Map<String,Object> map){
        Long goodsId = Long.valueOf((Integer)map.get("goodsId"));
        List<String> images = (List<String>)map.get("img");
        //先删除原有的图片
        goodInfoService.deleteImageByGoodsId(goodsId);
        GoodsAttach attach = new GoodsAttach();
        attach.setGoodsId(goodsId);
        int result = 0;
        for (String image:images){
            attach.setPath(image);
            goodInfoService.releteImage(attach);
            result++;
        }
        return HttpResult.success(result);
    }

    /**
     * 根据商品ID获取图片列表
     * @param goodsId
     * @return
     */
    @ResponseBody
    @GetMapping("/getImg")
    public HttpResult getImage(Long goodsId){
        List<GoodsAttach> list = goodInfoService.getImgs(goodsId);
        List<String> arrayList = new ArrayList<>();
        for(GoodsAttach attach:list){
            arrayList.add(attach.getPath());
        }
        return HttpResult.success(arrayList);
    }


    @PutMapping(value = "/StoreProduct")
    public HttpResult update(@RequestBody GoodsInfo info){
        int result = goodInfoService.updateGoods(info);
        return HttpResult.success(result);
    }
}
